package com.msy.controller;

import com.msy.dao.DepartmentDao;
import com.msy.dao.EmployeeDao;
import com.msy.pojo.Department;
import com.msy.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * @date 2020/11/17 - 10:47
 */
@Controller
public class EmployeeController {
    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    DepartmentDao departmentDao;

    @RequestMapping("/emps")
    public String emps(Model model) {
        Collection<Employee> allEmployees = employeeDao.getAllEmployees();
        model.addAttribute("emps", allEmployees);
        return "emp/list";
    }

    @GetMapping("/emp")
    public String addpage(Employee employee, Model model) {
        Collection<Department> departments = departmentDao.departments();
        model.addAttribute("departments", departments);
        return "emp/add";
    }

    @PostMapping("/emp")
    public String addemp(Employee employee) {
        System.out.println(employee);
        employeeDao.addEmployee(employee);
        return "redirect:/emps";
    }

    @RequestMapping("/edit/{id}")
    public String editpage(@PathVariable("id")Integer id,Model model){
        //查询指定id的员工,添加到empByID中,用于前端接收
        Employee employeeByID = employeeDao.getEmployeeByID(id);
        model.addAttribute("empByID", employeeByID);
        //查出所有的部门信息,添加到departments中,用于前端接收
        Collection<Department> departments = departmentDao.departments();
        model.addAttribute("departments", departments);
        return "emp/edit";
    }
    @PostMapping("/edit")
    public String updateemp(Employee employee){
        employeeDao.addEmployee(employee);
        return "redirect:/emps";
    }
    @RequestMapping("/delete/{id}")
    public String deleteemp(@PathVariable("id")Integer id){
        employeeDao.deleteEmployeeByID(id);
        return "redirect:/emps";
    }

}
